<template>
    <div>
        <a-row>
            <a-col :span="24">
                <a-form
                    :model="searchFormData"
                    name="horizontal_login"
                    layout="inline"
                    autocomplete="off"
                    @finish="onFinishSubmitSearch"
                    @finishFailed="onFinishFailedSearch">

                    <a-row type="flex"><#list tableData.request as item>
                        <a-col :span="5">
                            <a-form-item
                                label="${item.description!item.name}"
                                name="${item.name}">
                                <#if (item.hasItemData)>
                                <a-select v-model:value="searchFormData.${item.name}" placeholder="请选择${item.description!item.name}">
                                    <a-select-option value="">全部</a-select-option>
                                <#list item.items as item2>
                                    <a-select-option value="${item2.code}">${item2.value}</a-select-option>
                                </#list>
                                </a-select>
                                <#else>
                                <a-input v-model:value="searchFormData.${item.name}"></a-input>
                                </#if>
                            </a-form-item>
                        </a-col></#list>
                    </a-row>
                
                    <a-form-item>
                    	<a-button type="primary" html-type="submit">查询</a-button>
                    </a-form-item>
                    
                    <a-form-item>
                    	<a-button @click="onClickRevert">重置</a-button>
                    </a-form-item>
        		</a-form>
            </a-col>
        </a-row>
		
        <a-space style="margin-top: 20px;">
          <a-button type="primary" @click="onClickShowAdd${serviceName?cap_first}">添加</a-button>
          <a-button @click="update">刷新</a-button>
        </a-space>

        <a-row style="margin-top: 10px;">
            <a-col :span="24">
                <a-table :columns="columns" v-model:dataSource="list.value" :pagination="false">
                  <template #bodyCell="{column, record}">
                  <#list tableData.response as item>
                  	<#if (item.type?? && item.type=="boolean")>
                  	<template v-if="column.key === '${item.name}'">
                      <a-tag v-if="record.${item.name}" color="green">True</a-tag>
                      <a-tag v-else color="red">False</a-tag>
                    </template>
                    <#elseif (item.type?? && item.type=="#/definitions/MoneyRes")>
                    <template v-if="column.key === '${item.name}'">
                     ￥{{record.${item.name}.standardString}}
                    </template>
                  	</#if>
                  </#list>
                    <template v-if="column.key === '${config.keyField!}'">
                      <a @click="edit(record.${config.keyField!})">修改</a>
                      <a-divider type="vertical" style="height: 20px; border-color: #ccc" dashed />
					  <a-popconfirm
						title="确定要删除吗？"
						ok-text="确定"
						cancel-text="取消"
						placement="leftTop"
						@confirm="onClickIsDel(record.${config.keyField!})">
						<a href="#">删除</a>
					</a-popconfirm>
                    </template>
                    
                  </template>
                </a-table>
            </a-col>
        </a-row>

        <a-row style="margin-top: 20px;">
          <a-col>
            <a-pagination v-model:current="page" v-model:total="total" v-model:pageSize="limit" show-less-items @change="pageChange" />
          </a-col>
        </a-row>

        
        <a-form :model="add${serviceName?cap_first}FormData" ref="add${serviceName?cap_first}Form">
          <a-drawer v-model:visible="showAdd${serviceName?cap_first}Visible"
                      placement="right" title="添加${serviceName?cap_first}" width="800" :closable="false">
          
              <#if (addOpt??)>
              <#list addOpt.request as item>
              <#if (item.name!=config.keyField)>
              	<#if (!item.hasItemData)>
              	<#if (item.type=="boolean")>
              	<a-form-item label="${item.description!item.name}" name="${item.name}">
                  <a-switch v-model:checked="add${serviceName?cap_first}FormData.${item.name}"/>
	            </a-form-item>
              	<#else>
	            <a-form-item label="${item.description!item.name}" name="${item.name}">
              	<!--:rules="[{ required: true, message: '${item.description!item.name}' }]"-->
	              <a-input v-model:value="add${serviceName?cap_first}FormData.${item.name}"></a-input>
	            </a-form-item>
	            </#if>
	            <#else>
	            <a-form-item label="${item.description!item.name}" name="${item.name}">
                <a-select v-model:value="add${serviceName?cap_first}FormData.${item.name}" placeholder="请选择${item.description!item.name}">
                  <a-select-option v-for="tk in ${item.name}SelectData" :key="tk.value" :value="tk.value">{{tk.label}}</a-select-option>
                </a-select>
	            </a-form-item>
	            </#if>
	          </#if>
              </#list>
	          </#if>

              <template #extra>
                <a-button style="margin-right: 8px" @click="showAdd${serviceName?cap_first}Visible=false">取消</a-button>
                <a-button type="primary" @click="onClickSubmitAdd${serviceName?cap_first}">提交</a-button>
              </template>
          
          </a-drawer>
        </a-form>




        <a-form :model="edit${serviceName?cap_first}FormData" ref="edit${serviceName?cap_first}Form">
          <a-drawer v-model:visible="showEdit${serviceName?cap_first}Visible"
                    placement="right" title="修改${serviceDescription}" width="800" :closable="false">
				<#if (updateOpt??)>
				<#list updateOpt.request as item>
				<#if (item.name!=config.keyField)>
				<#if (!item.hasItemData)>
				<#if (item.type=="boolean")>
              	<a-form-item label="${item.description!item.name}" name="${item.name}">
                  <a-switch v-model:checked="edit${serviceName?cap_first}FormData.${item.name}"/>
	            </a-form-item>
	            <#else>
				<a-form-item label="${item.description!item.name}" name="${item.name}">
				<!--:rules="[{ required: true, message: '${item.description!item.name}' }]"-->
					<a-input v-model:value="edit${serviceName?cap_first}FormData.${item.name}"></a-input>
				</a-form-item>
				</#if>
				<#else>
				<a-form-item label="${item.description!item.name}" name="${item.name}">
                <a-select v-model:value="edit${serviceName?cap_first}FormData.${item.name}" placeholder="请选择${item.description!item.name}">
                  <a-select-option v-for="tk in ${item.name}SelectData" :key="tk.value" :value="tk.value">{{tk.label}}</a-select-option>
                </a-select>
	            </a-form-item>
				</#if>
				</#if>
				</#list>
				</#if>
				<template #extra>
				  <a-button style="margin-right: 8px" @click="showEdit${serviceName?cap_first}Visible=false">取消</a-button>
				  <a-button type="primary" @click="onClickSubmitEdit${serviceName?cap_first}">提交</a-button>
				</template>

          </a-drawer>
        </a-form>

    </div>
</template>

<script>
import { RequestAPI } from '@/common/fetch';
import { createVNode, reactive, ref, onMounted, unref } from 'vue'
import { message } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'

const columns = [
<#list tableData.response as item>
<#if (item.name!=config.keyField)>
  {
  	<#if item.description??>
    title: '${item.description?replace("'","\"")}',
    <#else>
    title: '${item.name}',
    </#if>
    dataIndex: '${item.name}',
    key: '${item.name}',
  },
</#if>
</#list>
  {
    title: '操作',
    dataIndex: '${config.keyField!}',
    key: '${config.keyField!}',
  }
]

export default{
    name: '${serviceName}',
    setup(){
    	<#if (addOpt??)>
		<#list addOpt.request as item>
		<#if (item.hasItemData)>
        let ${item.name}SelectData = ref([
		<#list item.items as item2>
            { value: ${item2.code}, label: '${item2.value}'}<#if item2_has_next>,</#if>
	    </#list>
        ])
		</#if>
		</#list>
		</#if>
		
        let limit = ref(20)
        let page = ref(1)
        let total = ref(1)

        const add${serviceName?cap_first}Form = ref(null)
        const showAdd${serviceName?cap_first}Visible = ref(false)
        
        const edit${serviceName?cap_first}Form = ref(null)
        const showEdit${serviceName?cap_first}Visible = ref(false)

        const searchFormData = ref({
            /*
            <#list tableData.request as item>
            ${item.name}: <#switch item.type>
			<#case "string">''<#break>
			<#case "integer">0<#break>
			<#case "boolean">false<#break>
			<#case "number">0<#break>
			<#default>${item.type}</#switch><#if item_has_next>,</#if>
            </#list>
            */
        })

        const add${serviceName?cap_first}FormData = reactive({
          <#if (addOpt??)>
          <#list addOpt.request as item>
          ${item.name}:''<#if item_has_next>,</#if>
          </#list>
          </#if>
        })

        const edit${serviceName?cap_first}FormData = ref({
          <#if (updateOpt??)>
          <#list updateOpt.request as item>
          ${item.name}:''<#if item_has_next>,</#if>
          </#list>
          </#if>
        })

        const list = reactive({value:[]})


        /**
         * 搜索提交
         */
        const onFinishSubmitSearch = () => {
          page.value = 1 // 搜索都是从第一页开始
          update() // 更新列表
        }

        /**
         * 搜索提交失败
         * @param {*} err 
         */
        const onFinishFailedSearch = (err) => {
          console.log('Failed:', err)
        }


        // const disabled = computed(() => {
        //     return !(searchFormData.tagName && searchFormData.isEnable);
        // })


        /**
         * 显示添加表单
         */
        const onClickShowAdd${serviceName?cap_first} = () => {
          showAdd${serviceName?cap_first}Visible.value = true
        }

        onMounted(()=>{
          update() // 更新列表
        })


        const onClickSubmitAdd${serviceName?cap_first} = () => {
          let form = unref(add${serviceName?cap_first}Form)
          try{
            let res = form.validate()
            if( res ){
              res.then(async e=>{
                
                console.log(e)
                await RequestAPI.add${serviceName?cap_first}(e, res=>{
                  if(res.success){
                    showAdd${serviceName?cap_first}Visible.value = false
                    message.success(res.message)
                    update() // 更新列表
                  }
                })
                

              }).catch(err=>{
                console.log('err')
              })
            }
          }catch(err){
            console.log('err')
          }
        }

        const del = async (id)=>{
          await RequestAPI.delete${serviceName?cap_first}([id], res=>{
            if(res.success){
              message.success(res.message)
              
            }
          })
          update() // 更新列表
        }

        const edit = async (id)=>{
          console.log(id)
          await RequestAPI.get${serviceName?cap_first}(id, res=>{
            if( res.success ){
              showEdit${serviceName?cap_first}Visible.value = true
              let data = Object.assign({}, res.data)
              <#if (detailOpt??)>
              <#list detailOpt.response as item>
              <#if (item.type?? && item.type=="#/definitions/MoneyRes")>
              data.${item.name} = res.data.${item.name}.standardString;
              </#if>
              </#list>
              </#if>
              edit${serviceName?cap_first}FormData.value = Object.assign({}, data)
            }
          })
        }

        /**
         * 修改服务
         */
        const onClickSubmitEdit${serviceName?cap_first} = ()=>{

          let form = unref(edit${serviceName?cap_first}Form)
          try{
            let res = form.validate()
            if( res ){
              res.then(async e=>{
                
                await RequestAPI.update${serviceName?cap_first}(Object.assign({}, edit${serviceName?cap_first}FormData.value), res=>{
                  if(res.success){
                    showEdit${serviceName?cap_first}Visible.value = false
                    message.success(res.message)
                    update() // 更新列表
                  }
                })

              }).catch(err=>{
                console.log('err')
              })
            }
          }catch(err){
            console.log('err')
          }

        }

        /**
         * 刷新页面
         */
        const update = async ()=>{
          let data = {
            <#list tableData.request as item>
            ${item.name}: searchFormData.value.${item.name}<#if item_has_next>,</#if>
            </#list>
          }
          await RequestAPI.get${serviceName?cap_first}List(data, res=>{
            if(res.success){
              list.value = res.data
              total.value = res.total
            }
          })
          // 清除新增数据绑定的值
          Object.assign(add${serviceName?cap_first}FormData, {
          <#if (addOpt??)>
          <#list addOpt.request as item>
          	${item.name}:''<#if item_has_next>,</#if>
          </#list>
          </#if>
          })
        }

        // 切换页面
        const pageChange = (p, s)=>{
          // console.log(page, pageSize)
          page.value = p
          update()
        }

        const onClickRevert = ()=>{
          searchFormData.value.tagName = ''
          searchFormData.value.isEnable = 'all'
        }

        const onClickIsDel = (id)=>{
			del(id)
        }

        return{
          columns, list, total, page, limit, pageChange, edit, del,
          searchFormData, onFinishSubmitSearch, onFinishFailedSearch,
          showAdd${serviceName?cap_first}Visible, add${serviceName?cap_first}FormData, add${serviceName?cap_first}Form, onClickShowAdd${serviceName?cap_first}, onClickSubmitAdd${serviceName?cap_first},
          showEdit${serviceName?cap_first}Visible, edit${serviceName?cap_first}FormData, edit${serviceName?cap_first}Form, onClickSubmitEdit${serviceName?cap_first},
          update, onClickRevert, onClickIsDel,<#if (addOpt??)><#list addOpt.request as item><#if (item.hasItemData)>${item.name}SelectData,</#if></#list></#if>
        }

    }
}
</script>